//  Copyright (c) 2010 Mahesh Sharma,Matt MacDonald
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

package org.prx.prp.view;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.prx.prp.IRockOnNextGenService;
import org.prx.prp.R;
import org.prx.prp.BackgroundPlaybackService;
import org.prx.prp.controller.ImageCacheManager;
import org.prx.prp.controller.SchedulingManager;
import org.prx.prp.controller.StreamManager;
import org.prx.prp.model.Scheduling;
import org.prx.prp.model.Stream;
import org.prx.prp.utility.DateParser;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class StationInformationView extends PRXCustomActivity {
	protected static final int SYNC_SUCC = 0;
	protected static final int SYNC_FAILED = 1;
	
	private boolean mServiceIsConnected = false;
	Stream stream;
	String programName;
	ListView listView;
	private Context mContext;
	ArrayList<Scheduling> scheduling;

	private Handler h = new Handler() {
		public void handleMessage(Message g) {
			switch (g.what) {
			case SYNC_SUCC:
				intent = new Intent(mContext, BackgroundPlaybackService.class);
				bindService(intent, mServiceConnection,
						Context.BIND_AUTO_CREATE);
				ImageView streamLogoImage = (ImageView) findViewById(R.id.stream_logo);
				if (scheduling.size() > 0) {
					programName = scheduling.get(0).getProgramTitle();
					adapter = new SchedulingListAdapter(mContext, scheduling,
							SchedulingListAdapter.SUMMARY);
					listView.setAdapter(adapter);
				} else {
					Toast msg = Toast.makeText(mContext,
							"Schedule not available", Toast.LENGTH_LONG);
					msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
							msg.getYOffset() / 2);
					msg.show();
				}

				if (imageBitmap == null)
					streamLogoImage.setImageResource(R.drawable.icon);
				else
					streamLogoImage.setImageBitmap(imageBitmap);

				final Intent intent = new Intent(mContext, StreamScheduleView.class);
				Bundle b23 = new Bundle();
				b23.putInt("STREAM_ID", stream.getStreamId());
				b23.putString("STREAM_DISPLAY_NAME", stream.getDisplayName());
				intent.putExtras(b23);
				listView.setOnItemClickListener(new OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						// TODO Auto-generated method stub

						if (position == scheduling.size()) {
							startActivity(intent);
						}
					}
				});
				break;
			case SYNC_FAILED:
				Toast msg = Toast.makeText(mContext, "Connection error",
						Toast.LENGTH_LONG);
				msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
						msg.getYOffset() / 2);
				msg.show();
				break;
			}
		}
	};
	private Intent intent;
	private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Toast msg = Toast.makeText(mContext,
					"Error in connecting to stream", Toast.LENGTH_LONG);
			msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
					msg.getYOffset() / 2);
			msg.show();
		}
	};

	private ServiceConnection mServiceConnection = new ServiceConnection() {
		private IRockOnNextGenService mService;

		public void onServiceConnected(ComponentName classname, IBinder obj) {
			mServiceIsConnected = true;
			mService = IRockOnNextGenService.Stub.asInterface(obj);
			final ImageButton playButton = (ImageButton) findViewById(R.id.station_play_button);
			playButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg) {
					if (stream.getStreamUrls().size() > 0) {
						try {

							mService.openFile(programName != null ? programName
									: "", stream.getDisplayName(), stream
									.getStreamUrls().get(0).getURL(),
									(int) stream.getStreamId());

							mService.play();
							Toast msg = Toast.makeText(mContext,
									"Starting buffering...", Toast.LENGTH_LONG);
							msg.setGravity(Gravity.CENTER,
									msg.getXOffset() / 2, msg.getYOffset() / 2);
							msg.show();
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			});
		}

		public void onServiceDisconnected(ComponentName classname) {
		}

	};

	private SchedulingListAdapter adapter;

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mServiceIsConnected){
			unbindService(mServiceConnection);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.streaminfoview);

		final int streamID = this.getIntent().getExtras().getInt("STREAM_ID");

		mContext = this;
		IntentFilter f = new IntentFilter();
		f.addAction("org.prx.errorInStream");
		this.registerReceiver(mIntentReceiver, new IntentFilter(f));
		final ImageButton favoriteImageButton = (ImageButton) findViewById(R.id.station_favorite_button);
		if (StreamManager.isFavorite(streamID))
			favoriteImageButton.setImageResource(R.drawable.tab_favorites);
		else
			favoriteImageButton.setImageResource(R.drawable.tab_no_favorite);
		favoriteImageButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (StreamManager.isFavorite(streamID)) {
					StreamManager.removeFavorite(streamID);
					favoriteImageButton.setImageResource(R.drawable.tab_no_favorite);
				} else {
					StreamManager.addFavorite(streamID);
					favoriteImageButton.setImageResource(R.drawable.tab_favorites);
				}
			}
		});
		stream = StreamManager.findById(streamID);
		TextView streamNameView = (TextView) findViewById(R.id.stream_name_1);
		TextView StreamNameViewSecondary = (TextView) findViewById(R.id.stream_name_2);
		streamNameView.setText(stream.getDisplayName());
		StreamNameViewSecondary.setText(stream.getDisplayName());
		TextView streamStateView = (TextView) findViewById(R.id.stream_state);
		streamStateView.setText(stream.getSource().getStatePrimary());
		listView = (ListView) findViewById(R.id.stream_schedule_list_2);
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				doUpdate();
			}
		});
		t1.start();
		Toast msg = Toast.makeText(mContext, "Getting stream schedule...",
				Toast.LENGTH_LONG);
		msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
				msg.getYOffset() / 2);
		msg.show();
	}

	Bitmap imageBitmap;

	private void doUpdate() {
		try {
			imageBitmap = ImageCacheManager.getInstance().getBitmapFromURL(
					stream.getLogoUrl(), 0);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			imageBitmap = null;
		}
		try {
			scheduling = SchedulingManager.getInstance().findAllByStream(
					stream.getStreamId(), 2);
		} catch (JSONException e) {
			h.sendEmptyMessage(SYNC_FAILED);
			return;
		}
		h.sendEmptyMessage(SYNC_SUCC);
	}
}

class SchedulingListAdapter extends BaseAdapter {
	final static int SUMMARY = 1;
	final static int ALL = 0;
	ArrayList<Scheduling> scheduling;
	private LayoutInflater mInflater;
	Context mContext;
	int type;
	Intent t;

	public SchedulingListAdapter(Context context,
			ArrayList<Scheduling> scheduling, int type) {
		this.mContext = context;
		this.scheduling = scheduling;
		mInflater = LayoutInflater.from(context);
		this.type = type;
	}

	public int getCount() {
		return scheduling.size() + type;
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View test = null;
		if (position < scheduling.size()) {
			final Scheduling s = scheduling.get(position);
			test = mInflater.inflate(R.layout.stream_schedule_item, null);
			TextView programNameTextView = (TextView) test.findViewById(R.id.program_name);
			programNameTextView.setText(s.getProgramTitle());
			TextView startTimeTextView = (TextView) test.findViewById(R.id.start_time);
			startTimeTextView.setText(DateParser.getTime(s.getStartTime()));
			TextView endTimeTextView = (TextView) test.findViewById(R.id.end_time);
			endTimeTextView.setText(DateParser.getTime(s.getEndTime()));
			TextView showProgram = (TextView) test
					.findViewById(R.id.show_program);
			if (s.programHasEpisodes()) {
				showProgram.setVisibility(ImageButton.VISIBLE);
				test.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Bundle b1 = new Bundle();
						b1.putInt("PROGRAM_ID", s.getProgramID());
						Intent i = new Intent(mContext, ProgramInfoView.class);
						i.putExtras(b1);
						mContext.startActivity(i);
					}
				});
			} else
				showProgram.setVisibility(ImageButton.INVISIBLE);
		} else if (type == SUMMARY)
			test = mInflater.inflate(R.layout.today_schedule, null);
		return test;
	}
}
